home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / cookielib.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  55KB  |  1,760 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. """HTTP cookie handling for web clients.
  5.  
  6. This module has (now fairly distant) origins in Gisle Aas' Perl module
  7. HTTP::Cookies, from the libwww-perl library.
  8.  
  9. Docstrings, comments and debug strings in this code refer to the
  10. attributes of the HTTP cookie system as cookie-attributes, to distinguish
  11. them clearly from Python attributes.
  12.  
  13. Class diagram (note that BSDDBCookieJar and the MSIE* classes are not
  14. distributed with the Python standard library, but are available from
  15. http://wwwsearch.sf.net/):
  16.  
  17.                         CookieJar____
  18.                         /     \\                  FileCookieJar      \\                   /    |   \\         \\       MozillaCookieJar | LWPCookieJar \\                        |               |                        |   ---MSIEBase |                         |  /      |     |                          | /   MSIEDBCookieJar BSDDBCookieJar
  19.                   |/
  20.                MSIECookieJar
  21.  
  22. """
  23. __all__ = [
  24.     'Cookie',
  25.     'CookieJar',
  26.     'CookiePolicy',
  27.     'DefaultCookiePolicy',
  28.     'FileCookieJar',
  29.     'LWPCookieJar',
  30.     'lwp_cookie_str',
  31.     'LoadError',
  32.     'MozillaCookieJar']
  33. import re
  34. import urlparse
  35. import copy
  36. import time
  37. import urllib
  38.  
  39. try:
  40.     import threading as _threading
  41. except ImportError:
  42.     import dummy_threading as _threading
  43.  
  44. import httplib
  45. from calendar import timegm
  46. debug = False
  47. logger = None
  48.  
  49. def _debug(*args):
  50.     global logger
  51.     if not debug:
  52.         return None
  53.     if not logger:
  54.         import logging as logging
  55.         logger = logging.getLogger('cookielib')
  56.     
  57.     return logger.debug(*args)
  58.  
  59. DEFAULT_HTTP_PORT = str(httplib.HTTP_PORT)
  60. MISSING_FILENAME_TEXT = 'a filename was not supplied (nor was the CookieJar instance initialised with one)'
  61.  
  62. def _warn_unhandled_exception():
  63.     import warnings as warnings
  64.     import traceback as traceback
  65.     import StringIO as StringIO
  66.     f = StringIO.StringIO()
  67.     traceback.print_exc(None, f)
  68.     msg = f.getvalue()
  69.     warnings.warn('cookielib bug!\n%s' % msg, stacklevel = 2)
  70.  
  71. EPOCH_YEAR = 1970
  72.  
  73. def _timegm(tt):
  74.     (year, month, mday, hour, min, sec) = tt[:6]
  75.     if year >= EPOCH_YEAR:
  76.         if month <= month:
  77.             pass
  78.         elif month <= 12:
  79.             if mday <= mday:
  80.                 pass
  81.             elif mday <= 31:
  82.                 if hour <= hour:
  83.                     pass
  84.                 elif hour <= 24:
  85.                     if min <= min:
  86.                         pass
  87.                     elif min <= 59:
  88.                         if sec <= sec:
  89.                             pass
  90.                         elif sec <= 61:
  91.                             return timegm(tt)
  92.     return None
  93.  
  94. DAYS = [
  95.     'Mon',
  96.     'Tue',
  97.     'Wed',
  98.     'Thu',
  99.     'Fri',
  100.     'Sat',
  101.     'Sun']
  102. MONTHS = [
  103.     'Jan',
  104.     'Feb',
  105.     'Mar',
  106.     'Apr',
  107.     'May',
  108.     'Jun',
  109.     'Jul',
  110.     'Aug',
  111.     'Sep',
  112.     'Oct',
  113.     'Nov',
  114.     'Dec']
  115. MONTHS_LOWER = []
  116. for month in MONTHS:
  117.     MONTHS_LOWER.append(month.lower())
  118.  
  119.  
  120. def time2isoz(t = None):
  121.     '''Return a string representing time in seconds since epoch, t.
  122.  
  123.     If the function is called without an argument, it will use the current
  124.     time.
  125.  
  126.     The format of the returned string is like "YYYY-MM-DD hh:mm:ssZ",
  127.     representing Universal Time (UTC, aka GMT).  An example of this format is:
  128.  
  129.     1994-11-24 08:49:37Z
  130.  
  131.     '''
  132.     if t is None:
  133.         t = time.time()
  134.     
  135.     (year, mon, mday, hour, min, sec) = time.gmtime(t)[:6]
  136.     return '%04d-%02d-%02d %02d:%02d:%02dZ' % (year, mon, mday, hour, min, sec)
  137.  
  138.  
  139. def time2netscape(t = None):
  140.     '''Return a string representing time in seconds since epoch, t.
  141.  
  142.     If the function is called without an argument, it will use the current
  143.     time.
  144.  
  145.     The format of the returned string is like this:
  146.  
  147.     Wed, DD-Mon-YYYY HH:MM:SS GMT
  148.  
  149.     '''
  150.     if t is None:
  151.         t = time.time()
  152.     
  153.     (year, mon, mday, hour, min, sec, wday) = time.gmtime(t)[:7]
  154.     return '%s %02d-%s-%04d %02d:%02d:%02d GMT' % (DAYS[wday], mday, MONTHS[mon - 1], year, hour, min, sec)
  155.  
  156. UTC_ZONES = {
  157.     'GMT': None,
  158.     'UTC': None,
  159.     'UT': None,
  160.     'Z': None }
  161. TIMEZONE_RE = re.compile('^([-+])?(\\d\\d?):?(\\d\\d)?$')
  162.  
  163. def offset_from_tz_string(tz):
  164.     offset = None
  165.     if tz in UTC_ZONES:
  166.         offset = 0
  167.     else:
  168.         m = TIMEZONE_RE.search(tz)
  169.         if m:
  170.             offset = 3600 * int(m.group(2))
  171.             if m.group(3):
  172.                 offset = offset + 60 * int(m.group(3))
  173.             
  174.             if m.group(1) == '-':
  175.                 offset = -offset
  176.             
  177.         
  178.     return offset
  179.  
  180.  
  181. def _str2time(day, mon, yr, hr, min, sec, tz):
  182.     
  183.     try:
  184.         mon = MONTHS_LOWER.index(mon.lower()) + 1
  185.     except ValueError:
  186.         
  187.         try:
  188.             imon = int(mon)
  189.         except ValueError:
  190.             return None
  191.  
  192.         if imon <= imon:
  193.             pass
  194.         elif imon <= 12:
  195.             mon = imon
  196.         else:
  197.             return None
  198.         imon <= 12
  199.  
  200.     if hr is None:
  201.         hr = 0
  202.     
  203.     if min is None:
  204.         min = 0
  205.     
  206.     if sec is None:
  207.         sec = 0
  208.     
  209.     yr = int(yr)
  210.     day = int(day)
  211.     hr = int(hr)
  212.     min = int(min)
  213.     sec = int(sec)
  214.     if yr < 1000:
  215.         cur_yr = time.localtime(time.time())[0]
  216.         m = cur_yr % 100
  217.         tmp = yr
  218.         yr = yr + cur_yr - m
  219.         m = m - tmp
  220.         if abs(m) > 50:
  221.             if m > 0:
  222.                 yr = yr + 100
  223.             else:
  224.                 yr = yr - 100
  225.         
  226.     
  227.     t = _timegm((yr, mon, day, hr, min, sec, tz))
  228.     if t is not None:
  229.         if tz is None:
  230.             tz = 'UTC'
  231.         
  232.         tz = tz.upper()
  233.         offset = offset_from_tz_string(tz)
  234.         if offset is None:
  235.             return None
  236.         t = t - offset
  237.     
  238.     return t
  239.  
  240. STRICT_DATE_RE = re.compile('^[SMTWF][a-z][a-z], (\\d\\d) ([JFMASOND][a-z][a-z]) (\\d\\d\\d\\d) (\\d\\d):(\\d\\d):(\\d\\d) GMT$')
  241. WEEKDAY_RE = re.compile('^(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)[a-z]*,?\\s*', re.I)
  242. LOOSE_HTTP_DATE_RE = re.compile('^\n    (\\d\\d?)            # day\n       (?:\\s+|[-\\/])\n    (\\w+)              # month\n        (?:\\s+|[-\\/])\n    (\\d+)              # year\n    (?:\n          (?:\\s+|:)    # separator before clock\n       (\\d\\d?):(\\d\\d)  # hour:min\n       (?::(\\d\\d))?    # optional seconds\n    )?                 # optional clock\n       \\s*\n    ([-+]?\\d{2,4}|(?![APap][Mm]\\b)[A-Za-z]+)? # timezone\n       \\s*\n    (?:\\(\\w+\\))?       # ASCII representation of timezone in parens.\n       \\s*$', re.X)
  243.  
  244. def http2time(text):
  245.     '''Returns time in seconds since epoch of time represented by a string.
  246.  
  247.     Return value is an integer.
  248.  
  249.     None is returned if the format of str is unrecognized, the time is outside
  250.     the representable range, or the timezone string is not recognized.  If the
  251.     string contains no timezone, UTC is assumed.
  252.  
  253.     The timezone in the string may be numerical (like "-0800" or "+0100") or a
  254.     string timezone (like "UTC", "GMT", "BST" or "EST").  Currently, only the
  255.     timezone strings equivalent to UTC (zero offset) are known to the function.
  256.  
  257.     The function loosely parses the following formats:
  258.  
  259.     Wed, 09 Feb 1994 22:23:32 GMT       -- HTTP format
  260.     Tuesday, 08-Feb-94 14:15:29 GMT     -- old rfc850 HTTP format
  261.     Tuesday, 08-Feb-1994 14:15:29 GMT   -- broken rfc850 HTTP format
  262.     09 Feb 1994 22:23:32 GMT            -- HTTP format (no weekday)
  263.     08-Feb-94 14:15:29 GMT              -- rfc850 format (no weekday)
  264.     08-Feb-1994 14:15:29 GMT            -- broken rfc850 format (no weekday)
  265.  
  266.     The parser ignores leading and trailing whitespace.  The time may be
  267.     absent.
  268.  
  269.     If the year is given with only 2 digits, the function will select the
  270.     century that makes the year closest to the current date.
  271.  
  272.     '''
  273.     m = STRICT_DATE_RE.search(text)
  274.     if m:
  275.         g = m.groups()
  276.         mon = MONTHS_LOWER.index(g[1].lower()) + 1
  277.         tt = (int(g[2]), mon, int(g[0]), int(g[3]), int(g[4]), float(g[5]))
  278.         return _timegm(tt)
  279.     text = text.lstrip()
  280.     text = WEEKDAY_RE.sub('', text, 1)
  281.     (day, mon, yr, hr, min, sec, tz) = [
  282.         None] * 7
  283.     m = LOOSE_HTTP_DATE_RE.search(text)
  284.     if m is not None:
  285.         (day, mon, yr, hr, min, sec, tz) = m.groups()
  286.     else:
  287.         return None
  288.     return m(day, mon, yr, hr, min, sec, tz)
  289.  
  290. ISO_DATE_RE = re.compile('^\n    (\\d{4})              # year\n       [-\\/]?\n    (\\d\\d?)              # numerical month\n       [-\\/]?\n    (\\d\\d?)              # day\n   (?:\n         (?:\\s+|[-:Tt])  # separator before clock\n      (\\d\\d?):?(\\d\\d)    # hour:min\n      (?::?(\\d\\d(?:\\.\\d*)?))?  # optional seconds (and fractional)\n   )?                    # optional clock\n      \\s*\n   ([-+]?\\d\\d?:?(:?\\d\\d)?\n    |Z|z)?               # timezone  (Z is "zero meridian", i.e. GMT)\n      \\s*$', re.X)
  291.  
  292. def iso2time(text):
  293.     '''
  294.     As for http2time, but parses the ISO 8601 formats:
  295.  
  296.     1994-02-03 14:15:29 -0100    -- ISO 8601 format
  297.     1994-02-03 14:15:29          -- zone is optional
  298.     1994-02-03                   -- only date
  299.     1994-02-03T14:15:29          -- Use T as separator
  300.     19940203T141529Z             -- ISO 8601 compact format
  301.     19940203                     -- only date
  302.  
  303.     '''
  304.     text = text.lstrip()
  305.     (day, mon, yr, hr, min, sec, tz) = [
  306.         None] * 7
  307.     m = ISO_DATE_RE.search(text)
  308.     if m is not None:
  309.         (yr, mon, day, hr, min, sec, tz, _) = m.groups()
  310.     else:
  311.         return None
  312.     return m is not None(day, mon, yr, hr, min, sec, tz)
  313.  
  314.  
  315. def unmatched(match):
  316.     '''Return unmatched part of re.Match object.'''
  317.     (start, end) = match.span(0)
  318.     return match.string[:start] + match.string[end:]
  319.  
  320. HEADER_TOKEN_RE = re.compile('^\\s*([^=\\s;,]+)')
  321. HEADER_QUOTED_VALUE_RE = re.compile('^\\s*=\\s*\\"([^\\"\\\\]*(?:\\\\.[^\\"\\\\]*)*)\\"')
  322. HEADER_VALUE_RE = re.compile('^\\s*=\\s*([^\\s;,]*)')
  323. HEADER_ESCAPE_RE = re.compile('\\\\(.)')
  324.  
  325. def split_header_words(header_values):
  326.     '''Parse header values into a list of lists containing key,value pairs.
  327.  
  328.     The function knows how to deal with ",", ";" and "=" as well as quoted
  329.     values after "=".  A list of space separated tokens are parsed as if they
  330.     were separated by ";".
  331.  
  332.     If the header_values passed as argument contains multiple values, then they
  333.     are treated as if they were a single value separated by comma ",".
  334.  
  335.     This means that this function is useful for parsing header fields that
  336.     follow this syntax (BNF as from the HTTP/1.1 specification, but we relax
  337.     the requirement for tokens).
  338.  
  339.       headers           = #header
  340.       header            = (token | parameter) *( [";"] (token | parameter))
  341.  
  342.       token             = 1*<any CHAR except CTLs or separators>
  343.       separators        = "(" | ")" | "<" | ">" | "@"
  344.                         | "," | ";" | ":" | "\\" | <">
  345.                         | "/" | "[" | "]" | "?" | "="
  346.                         | "{" | "}" | SP | HT
  347.  
  348.       quoted-string     = ( <"> *(qdtext | quoted-pair ) <"> )
  349.       qdtext            = <any TEXT except <">>
  350.       quoted-pair       = "\\" CHAR
  351.  
  352.       parameter         = attribute "=" value
  353.       attribute         = token
  354.       value             = token | quoted-string
  355.  
  356.     Each header is represented by a list of key/value pairs.  The value for a
  357.     simple token (not part of a parameter) is None.  Syntactically incorrect
  358.     headers will not necessarily be parsed as you would want.
  359.  
  360.     This is easier to describe with some examples:
  361.  
  362.     >>> split_header_words([\'foo="bar"; port="80,81"; discard, bar=baz\'])
  363.     [[(\'foo\', \'bar\'), (\'port\', \'80,81\'), (\'discard\', None)], [(\'bar\', \'baz\')]]
  364.     >>> split_header_words([\'text/html; charset="iso-8859-1"\'])
  365.     [[(\'text/html\', None), (\'charset\', \'iso-8859-1\')]]
  366.     >>> split_header_words([r\'Basic realm="\\"foo\\bar\\""\'])
  367.     [[(\'Basic\', None), (\'realm\', \'"foobar"\')]]
  368.  
  369.     '''
  370.     if not not isinstance(header_values, basestring):
  371.         raise AssertionError
  372.     result = []
  373.     for text in header_values:
  374.         orig_text = text
  375.         pairs = []
  376.         while text:
  377.             m = HEADER_TOKEN_RE.search(text)
  378.             if m:
  379.                 text = unmatched(m)
  380.                 name = m.group(1)
  381.                 m = HEADER_QUOTED_VALUE_RE.search(text)
  382.                 if m:
  383.                     text = unmatched(m)
  384.                     value = m.group(1)
  385.                     value = HEADER_ESCAPE_RE.sub('\\1', value)
  386.                 else:
  387.                     m = HEADER_VALUE_RE.search(text)
  388.                     if m:
  389.                         text = unmatched(m)
  390.                         value = m.group(1)
  391.                         value = value.rstrip()
  392.                     else:
  393.                         value = None
  394.                 pairs.append((name, value))
  395.                 continue
  396.             if text.lstrip().startswith(','):
  397.                 text = text.lstrip()[1:]
  398.                 if pairs:
  399.                     result.append(pairs)
  400.                 
  401.                 pairs = []
  402.                 continue
  403.             (non_junk, nr_junk_chars) = re.subn('^[=\\s;]*', '', text)
  404.             if not nr_junk_chars > 0:
  405.                 raise AssertionError, "split_header_words bug: '%s', '%s', %s" % (orig_text, text, pairs)
  406.             text = non_junk
  407.             continue
  408.             nr_junk_chars > 0
  409.         if pairs:
  410.             result.append(pairs)
  411.             continue
  412.     
  413.     return result
  414.  
  415. HEADER_JOIN_ESCAPE_RE = re.compile('([\\"\\\\])')
  416.  
  417. def join_header_words(lists):
  418.     '''Do the inverse (almost) of the conversion done by split_header_words.
  419.  
  420.     Takes a list of lists of (key, value) pairs and produces a single header
  421.     value.  Attribute values are quoted if needed.
  422.  
  423.     >>> join_header_words([[("text/plain", None), ("charset", "iso-8859/1")]])
  424.     \'text/plain; charset="iso-8859/1"\'
  425.     >>> join_header_words([[("text/plain", None)], [("charset", "iso-8859/1")]])
  426.     \'text/plain, charset="iso-8859/1"\'
  427.  
  428.     '''
  429.     headers = []
  430.     for pairs in lists:
  431.         attr = []
  432.         for k, v in pairs:
  433.             if v is not None:
  434.                 if not re.search('^\\w+$', v):
  435.                     v = HEADER_JOIN_ESCAPE_RE.sub('\\\\\\1', v)
  436.                     v = '"%s"' % v
  437.                 
  438.                 k = '%s=%s' % (k, v)
  439.             
  440.             attr.append(k)
  441.         
  442.         if attr:
  443.             headers.append('; '.join(attr))
  444.             continue
  445.     
  446.     return ', '.join(headers)
  447.  
  448.  
  449. def parse_ns_headers(ns_headers):
  450.     '''Ad-hoc parser for Netscape protocol cookie-attributes.
  451.  
  452.     The old Netscape cookie format for Set-Cookie can for instance contain
  453.     an unquoted "," in the expires field, so we have to use this ad-hoc
  454.     parser instead of split_header_words.
  455.  
  456.     XXX This may not make the best possible effort to parse all the crap
  457.     that Netscape Cookie headers contain.  Ronald Tschalar\'s HTTPClient
  458.     parser is probably better, so could do worse than following that if
  459.     this ever gives any trouble.
  460.  
  461.     Currently, this is also used for parsing RFC 2109 cookies.
  462.  
  463.     '''
  464.     known_attrs = ('expires', 'domain', 'path', 'secure', 'port', 'max-age')
  465.     result = []
  466.     for ns_header in ns_headers:
  467.         pairs = []
  468.         version_set = False
  469.         for ii, param in enumerate(re.split(';\\s*', ns_header)):
  470.             param = param.rstrip()
  471.             if param == '':
  472.                 continue
  473.             
  474.             if '=' not in param:
  475.                 k = param
  476.                 v = None
  477.             else:
  478.                 (k, v) = re.split('\\s*=\\s*', param, 1)
  479.                 k = k.lstrip()
  480.             if ii != 0:
  481.                 lc = k.lower()
  482.                 if lc in known_attrs:
  483.                     k = lc
  484.                 
  485.                 if k == 'version':
  486.                     version_set = True
  487.                 
  488.                 if k == 'expires':
  489.                     if v.startswith('"'):
  490.                         v = v[1:]
  491.                     
  492.                     if v.endswith('"'):
  493.                         v = v[:-1]
  494.                     
  495.                     v = http2time(v)
  496.                 
  497.             
  498.             pairs.append((k, v))
  499.         
  500.         if pairs:
  501.             if not version_set:
  502.                 pairs.append(('version', '0'))
  503.             
  504.             result.append(pairs)
  505.             continue
  506.     
  507.     return result
  508.  
  509. IPV4_RE = re.compile('\\.\\d+$')
  510.  
  511. def is_HDN(text):
  512.     '''Return True if text is a host domain name.'''
  513.     if IPV4_RE.search(text):
  514.         return False
  515.     if text == '':
  516.         return False
  517.     if text[0] == '.' or text[-1] == '.':
  518.         return False
  519.     return True
  520.  
  521.  
  522. def domain_match(A, B):
  523.     """Return True if domain A domain-matches domain B, according to RFC 2965.
  524.  
  525.     A and B may be host domain names or IP addresses.
  526.  
  527.     RFC 2965, section 1:
  528.  
  529.     Host names can be specified either as an IP address or a HDN string.
  530.     Sometimes we compare one host name with another.  (Such comparisons SHALL
  531.     be case-insensitive.)  Host A's name domain-matches host B's if
  532.  
  533.          *  their host name strings string-compare equal; or
  534.  
  535.          * A is a HDN string and has the form NB, where N is a non-empty
  536.             name string, B has the form .B', and B' is a HDN string.  (So,
  537.             x.y.com domain-matches .Y.com but not Y.com.)
  538.  
  539.     Note that domain-match is not a commutative operation: a.b.c.com
  540.     domain-matches .c.com, but not the reverse.
  541.  
  542.     """
  543.     A = A.lower()
  544.     B = B.lower()
  545.     if A == B:
  546.         return True
  547.     if not is_HDN(A):
  548.         return False
  549.     i = A.rfind(B)
  550.     if i == -1 or i == 0:
  551.         return False
  552.     if not B.startswith('.'):
  553.         return False
  554.     if not is_HDN(B[1:]):
  555.         return False
  556.     return True
  557.  
  558.  
  559. def liberal_is_HDN(text):
  560.     '''Return True if text is a sort-of-like a host domain name.
  561.  
  562.     For accepting/blocking domains.
  563.  
  564.     '''
  565.     if IPV4_RE.search(text):
  566.         return False
  567.     return True
  568.  
  569.  
  570. def user_domain_match(A, B):
  571.     '''For blocking/accepting domains.
  572.  
  573.     A and B may be host domain names or IP addresses.
  574.  
  575.     '''
  576.     A = A.lower()
  577.     B = B.lower()
  578.     if not liberal_is_HDN(A) and liberal_is_HDN(B):
  579.         if A == B:
  580.             return True
  581.         return False
  582.     initial_dot = B.startswith('.')
  583.     if initial_dot and A.endswith(B):
  584.         return True
  585.     if not initial_dot and A == B:
  586.         return True
  587.     return False
  588.  
  589. cut_port_re = re.compile(':\\d+$')
  590.  
  591. def request_host(request):
  592.     '''Return request-host, as defined by RFC 2965.
  593.  
  594.     Variation from RFC: returned value is lowercased, for convenient
  595.     comparison.
  596.  
  597.     '''
  598.     url = request.get_full_url()
  599.     host = urlparse.urlparse(url)[1]
  600.     if host == '':
  601.         host = request.get_header('Host', '')
  602.     
  603.     host = cut_port_re.sub('', host, 1)
  604.     return host.lower()
  605.  
  606.  
  607. def eff_request_host(request):
  608.     '''Return a tuple (request-host, effective request-host name).
  609.  
  610.     As defined by RFC 2965, except both are lowercased.
  611.  
  612.     '''
  613.     erhn = req_host = request_host(request)
  614.     if req_host.find('.') == -1 and not IPV4_RE.search(req_host):
  615.         erhn = req_host + '.local'
  616.     
  617.     return (req_host, erhn)
  618.  
  619.  
  620. def request_path(request):
  621.     '''request-URI, as defined by RFC 2965.'''
  622.     url = request.get_full_url()
  623.     (path, parameters, query, frag) = urlparse.urlparse(url)[2:]
  624.     if parameters:
  625.         path = '%s;%s' % (path, parameters)
  626.     
  627.     path = escape_path(path)
  628.     req_path = urlparse.urlunparse(('', '', path, '', query, frag))
  629.     if not req_path.startswith('/'):
  630.         req_path = '/' + req_path
  631.     
  632.     return req_path
  633.  
  634.  
  635. def request_port(request):
  636.     host = request.get_host()
  637.     i = host.find(':')
  638.     if i >= 0:
  639.         port = host[i + 1:]
  640.         
  641.         try:
  642.             int(port)
  643.         except ValueError:
  644.             _debug("nonnumeric port: '%s'", port)
  645.             return None
  646.         
  647.  
  648.     None<EXCEPTION MATCH>ValueError
  649.     port = DEFAULT_HTTP_PORT
  650.     return port
  651.  
  652. HTTP_PATH_SAFE = "%/;:@&=+$,!~*'()"
  653. ESCAPED_CHAR_RE = re.compile('%([0-9a-fA-F][0-9a-fA-F])')
  654.  
  655. def uppercase_escaped_char(match):
  656.     return '%%%s' % match.group(1).upper()
  657.  
  658.  
  659. def escape_path(path):
  660.     '''Escape any invalid characters in HTTP URL, and uppercase all escapes.'''
  661.     if isinstance(path, unicode):
  662.         path = path.encode('utf-8')
  663.     
  664.     path = urllib.quote(path, HTTP_PATH_SAFE)
  665.     path = ESCAPED_CHAR_RE.sub(uppercase_escaped_char, path)
  666.     return path
  667.  
  668.  
  669. def reach(h):
  670.     '''Return reach of host h, as defined by RFC 2965, section 1.
  671.  
  672.     The reach R of a host name H is defined as follows:
  673.  
  674.        *  If
  675.  
  676.           -  H is the host domain name of a host; and,
  677.  
  678.           -  H has the form A.B; and
  679.  
  680.           -  A has no embedded (that is, interior) dots; and
  681.  
  682.           -  B has at least one embedded dot, or B is the string "local".
  683.              then the reach of H is .B.
  684.  
  685.        *  Otherwise, the reach of H is H.
  686.  
  687.     >>> reach("www.acme.com")
  688.     \'.acme.com\'
  689.     >>> reach("acme.com")
  690.     \'acme.com\'
  691.     >>> reach("acme.local")
  692.     \'.local\'
  693.  
  694.     '''
  695.     i = h.find('.')
  696.     if i >= 0:
  697.         b = h[i + 1:]
  698.         i = b.find('.')
  699.         if is_HDN(h):
  700.             if i >= 0 or b == 'local':
  701.                 return '.' + b
  702.         
  703.     return h
  704.  
  705.  
  706. def is_third_party(request):
  707.     '''
  708.  
  709.     RFC 2965, section 3.3.6:
  710.  
  711.         An unverifiable transaction is to a third-party host if its request-
  712.         host U does not domain-match the reach R of the request-host O in the
  713.         origin transaction.
  714.  
  715.     '''
  716.     req_host = request_host(request)
  717.     if not domain_match(req_host, reach(request.get_origin_req_host())):
  718.         return True
  719.     return False
  720.  
  721.  
  722. class Cookie:
  723.     '''HTTP Cookie.
  724.  
  725.     This class represents both Netscape and RFC 2965 cookies.
  726.  
  727.     This is deliberately a very simple class.  It just holds attributes.  It\'s
  728.     possible to construct Cookie instances that don\'t comply with the cookie
  729.     standards.  CookieJar.make_cookies is the factory function for Cookie
  730.     objects -- it deals with cookie parsing, supplying defaults, and
  731.     normalising to the representation used in this class.  CookiePolicy is
  732.     responsible for checking them to see whether they should be accepted from
  733.     and returned to the server.
  734.  
  735.     Note that the port may be present in the headers, but unspecified ("Port"
  736.     rather than"Port=80", for example); if this is the case, port is None.
  737.  
  738.     '''
  739.     
  740.     def __init__(self, version, name, value, port, port_specified, domain, domain_specified, domain_initial_dot, path, path_specified, secure, expires, discard, comment, comment_url, rest, rfc2109 = False):
  741.         if version is not None:
  742.             version = int(version)
  743.         
  744.         if expires is not None:
  745.             expires = int(expires)
  746.         
  747.         if port is None and port_specified is True:
  748.             raise ValueError('if port is None, port_specified must be false')
  749.         port_specified is True
  750.         self.version = version
  751.         self.name = name
  752.         self.value = value
  753.         self.port = port
  754.         self.port_specified = port_specified
  755.         self.domain = domain.lower()
  756.         self.domain_specified = domain_specified
  757.         self.domain_initial_dot = domain_initial_dot
  758.         self.path = path
  759.         self.path_specified = path_specified
  760.         self.secure = secure
  761.         self.expires = expires
  762.         self.discard = discard
  763.         self.comment = comment
  764.         self.comment_url = comment_url
  765.         self.rfc2109 = rfc2109
  766.         self._rest = copy.copy(rest)
  767.  
  768.     
  769.     def has_nonstandard_attr(self, name):
  770.         return name in self._rest
  771.  
  772.     
  773.     def get_nonstandard_attr(self, name, default = None):
  774.         return self._rest.get(name, default)
  775.  
  776.     
  777.     def set_nonstandard_attr(self, name, value):
  778.         self._rest[name] = value
  779.  
  780.     
  781.     def is_expired(self, now = None):
  782.         if now is None:
  783.             now = time.time()
  784.         
  785.         if self.expires is not None and self.expires <= now:
  786.             return True
  787.         return False
  788.  
  789.     
  790.     def __str__(self):
  791.         if self.port is None:
  792.             p = ''
  793.         else:
  794.             p = ':' + self.port
  795.         limit = self.domain + p + self.path
  796.         if self.value is not None:
  797.             namevalue = '%s=%s' % (self.name, self.value)
  798.         else:
  799.             namevalue = self.name
  800.         return '<Cookie %s for %s>' % (namevalue, limit)
  801.  
  802.     
  803.     def __repr__(self):
  804.         args = []
  805.         for name in ('version', 'name', 'value', 'port', 'port_specified', 'domain', 'domain_specified', 'domain_initial_dot', 'path', 'path_specified', 'secure', 'expires', 'discard', 'comment', 'comment_url'):
  806.             attr = getattr(self, name)
  807.             args.append('%s=%s' % (name, repr(attr)))
  808.         
  809.         args.append('rest=%s' % repr(self._rest))
  810.         args.append('rfc2109=%s' % repr(self.rfc2109))
  811.         return 'Cookie(%s)' % ', '.join(args)
  812.  
  813.  
  814.  
  815. class CookiePolicy:
  816.     '''Defines which cookies get accepted from and returned to server.
  817.  
  818.     May also modify cookies, though this is probably a bad idea.
  819.  
  820.     The subclass DefaultCookiePolicy defines the standard rules for Netscape
  821.     and RFC 2965 cookies -- override that if you want a customised policy.
  822.  
  823.     '''
  824.     
  825.     def set_ok(self, cookie, request):
  826.         '''Return true if (and only if) cookie should be accepted from server.
  827.  
  828.         Currently, pre-expired cookies never get this far -- the CookieJar
  829.         class deletes such cookies itself.
  830.  
  831.         '''
  832.         raise NotImplementedError()
  833.  
  834.     
  835.     def return_ok(self, cookie, request):
  836.         '''Return true if (and only if) cookie should be returned to server.'''
  837.         raise NotImplementedError()
  838.  
  839.     
  840.     def domain_return_ok(self, domain, request):
  841.         '''Return false if cookies should not be returned, given cookie domain.
  842.         '''
  843.         return True
  844.  
  845.     
  846.     def path_return_ok(self, path, request):
  847.         '''Return false if cookies should not be returned, given cookie path.
  848.         '''
  849.         return True
  850.  
  851.  
  852.  
  853. class DefaultCookiePolicy(CookiePolicy):
  854.     '''Implements the standard rules for accepting and returning cookies.'''
  855.     DomainStrictNoDots = 1
  856.     DomainStrictNonDomain = 2
  857.     DomainRFC2965Match = 4
  858.     DomainLiberal = 0
  859.     DomainStrict = DomainStrictNoDots | DomainStrictNonDomain
  860.     
  861.     def __init__(self, blocked_domains = None, allowed_domains = None, netscape = True, rfc2965 = False, rfc2109_as_netscape = None, hide_cookie2 = False, strict_domain = False, strict_rfc2965_unverifiable = True, strict_ns_unverifiable = False, strict_ns_domain = DomainLiberal, strict_ns_set_initial_dollar = False, strict_ns_set_path = False):
  862.         '''Constructor arguments should be passed as keyword arguments only.'''
  863.         self.netscape = netscape
  864.         self.rfc2965 = rfc2965
  865.         self.rfc2109_as_netscape = rfc2109_as_netscape
  866.         self.hide_cookie2 = hide_cookie2
  867.         self.strict_domain = strict_domain
  868.         self.strict_rfc2965_unverifiable = strict_rfc2965_unverifiable
  869.         self.strict_ns_unverifiable = strict_ns_unverifiable
  870.         self.strict_ns_domain = strict_ns_domain
  871.         self.strict_ns_set_initial_dollar = strict_ns_set_initial_dollar
  872.         self.strict_ns_set_path = strict_ns_set_path
  873.         if blocked_domains is not None:
  874.             self._blocked_domains = tuple(blocked_domains)
  875.         else:
  876.             self._blocked_domains = ()
  877.         if allowed_domains is not None:
  878.             allowed_domains = tuple(allowed_domains)
  879.         
  880.         self._allowed_domains = allowed_domains
  881.  
  882.     
  883.     def blocked_domains(self):
  884.         '''Return the sequence of blocked domains (as a tuple).'''
  885.         return self._blocked_domains
  886.  
  887.     
  888.     def set_blocked_domains(self, blocked_domains):
  889.         '''Set the sequence of blocked domains.'''
  890.         self._blocked_domains = tuple(blocked_domains)
  891.  
  892.     
  893.     def is_blocked(self, domain):
  894.         for blocked_domain in self._blocked_domains:
  895.             if user_domain_match(domain, blocked_domain):
  896.                 return True
  897.         
  898.         return False
  899.  
  900.     
  901.     def allowed_domains(self):
  902.         '''Return None, or the sequence of allowed domains (as a tuple).'''
  903.         return self._allowed_domains
  904.  
  905.     
  906.     def set_allowed_domains(self, allowed_domains):
  907.         '''Set the sequence of allowed domains, or None.'''
  908.         if allowed_domains is not None:
  909.             allowed_domains = tuple(allowed_domains)
  910.         
  911.         self._allowed_domains = allowed_domains
  912.  
  913.     
  914.     def is_not_allowed(self, domain):
  915.         if self._allowed_domains is None:
  916.             return False
  917.         for allowed_domain in self._allowed_domains:
  918.             if user_domain_match(domain, allowed_domain):
  919.                 return False
  920.         
  921.         return True
  922.  
  923.     
  924.     def set_ok(self, cookie, request):
  925.         '''
  926.         If you override .set_ok(), be sure to call this method.  If it returns
  927.         false, so should your subclass (assuming your subclass wants to be more
  928.         strict about which cookies to accept).
  929.  
  930.         '''
  931.         _debug(' - checking cookie %s=%s', cookie.name, cookie.value)
  932.         if not cookie.name is not None:
  933.             raise AssertionError
  934.         for n in ('version', 'verifiability', 'name', 'path', 'domain', 'port'):
  935.             fn_name = 'set_ok_' + n
  936.             fn = getattr(self, fn_name)
  937.             if not fn(cookie, request):
  938.                 return False
  939.         
  940.         return True
  941.  
  942.     
  943.     def set_ok_version(self, cookie, request):
  944.         if cookie.version is None:
  945.             _debug('   Set-Cookie2 without version attribute (%s=%s)', cookie.name, cookie.value)
  946.             return False
  947.         if cookie.version > 0 and not (self.rfc2965):
  948.             _debug('   RFC 2965 cookies are switched off')
  949.             return False
  950.         if cookie.version == 0 and not (self.netscape):
  951.             _debug('   Netscape cookies are switched off')
  952.             return False
  953.         return True
  954.  
  955.     
  956.     def set_ok_verifiability(self, cookie, request):
  957.         return True
  958.  
  959.     
  960.     def set_ok_name(self, cookie, request):
  961.         if cookie.version == 0 and self.strict_ns_set_initial_dollar and cookie.name.startswith('$'):
  962.             _debug("   illegal name (starts with '$'): '%s'", cookie.name)
  963.             return False
  964.         return True
  965.  
  966.     
  967.     def set_ok_path(self, cookie, request):
  968.         if cookie.path_specified:
  969.             req_path = request_path(request)
  970.             if (cookie.version > 0 or cookie.version == 0 or self.strict_ns_set_path) and not req_path.startswith(cookie.path):
  971.                 _debug('   path attribute %s is not a prefix of request path %s', cookie.path, req_path)
  972.                 return False
  973.         
  974.         return True
  975.  
  976.     
  977.     def set_ok_domain(self, cookie, request):
  978.         if self.is_blocked(cookie.domain):
  979.             _debug('   domain %s is in user block-list', cookie.domain)
  980.             return False
  981.         if self.is_not_allowed(cookie.domain):
  982.             _debug('   domain %s is not in user allow-list', cookie.domain)
  983.             return False
  984.         if cookie.domain_specified:
  985.             (req_host, erhn) = eff_request_host(request)
  986.             domain = cookie.domain
  987.             if domain.startswith('.'):
  988.                 undotted_domain = domain[1:]
  989.             else:
  990.                 undotted_domain = domain
  991.             embedded_dots = undotted_domain.find('.') >= 0
  992.             if not embedded_dots and domain != '.local':
  993.                 _debug('   non-local domain %s contains no embedded dot', domain)
  994.                 return False
  995.             if cookie.version > 0 or self.strict_ns_domain & self.DomainStrictNoDots:
  996.                 host_prefix = req_host[:-len(domain)]
  997.                 if host_prefix.find('.') >= 0 and not IPV4_RE.search(req_host):
  998.                     _debug('   host prefix %s for domain %s contains a dot', host_prefix, domain)
  999.                     return False
  1000.             
  1001.         
  1002.         return True
  1003.  
  1004.     
  1005.     def set_ok_port(self, cookie, request):
  1006.         if cookie.port_specified:
  1007.             req_port = request_port(request)
  1008.             if req_port is None:
  1009.                 req_port = '80'
  1010.             else:
  1011.                 req_port = str(req_port)
  1012.             for p in cookie.port.split(','):
  1013.                 
  1014.                 try:
  1015.                     int(p)
  1016.                 except ValueError:
  1017.                     _debug('   bad port %s (not numeric)', p)
  1018.                     return False
  1019.  
  1020.                 if p == req_port:
  1021.                     break
  1022.                     continue
  1023.             else:
  1024.                 return False
  1025.         return True
  1026.  
  1027.     
  1028.     def return_ok(self, cookie, request):
  1029.         '''
  1030.         If you override .return_ok(), be sure to call this method.  If it
  1031.         returns false, so should your subclass (assuming your subclass wants to
  1032.         be more strict about which cookies to return).
  1033.  
  1034.         '''
  1035.         _debug(' - checking cookie %s=%s', cookie.name, cookie.value)
  1036.         for n in ('version', 'verifiability', 'secure', 'expires', 'port', 'domain'):
  1037.             fn_name = 'return_ok_' + n
  1038.             fn = getattr(self, fn_name)
  1039.             if not fn(cookie, request):
  1040.                 return False
  1041.         
  1042.         return True
  1043.  
  1044.     
  1045.     def return_ok_version(self, cookie, request):
  1046.         if cookie.version > 0 and not (self.rfc2965):
  1047.             _debug('   RFC 2965 cookies are switched off')
  1048.             return False
  1049.         if cookie.version == 0 and not (self.netscape):
  1050.             _debug('   Netscape cookies are switched off')
  1051.             return False
  1052.         return True
  1053.  
  1054.     
  1055.     def return_ok_verifiability(self, cookie, request):
  1056.         return True
  1057.  
  1058.     
  1059.     def return_ok_secure(self, cookie, request):
  1060.         if cookie.secure and request.get_type() != 'https':
  1061.             _debug('   secure cookie with non-secure request')
  1062.             return False
  1063.         return True
  1064.  
  1065.     
  1066.     def return_ok_expires(self, cookie, request):
  1067.         if cookie.is_expired(self._now):
  1068.             _debug('   cookie expired')
  1069.             return False
  1070.         return True
  1071.  
  1072.     
  1073.     def return_ok_port(self, cookie, request):
  1074.         if cookie.port:
  1075.             req_port = request_port(request)
  1076.             if req_port is None:
  1077.                 req_port = '80'
  1078.             
  1079.             for p in cookie.port.split(','):
  1080.                 if p == req_port:
  1081.                     break
  1082.                     continue
  1083.             else:
  1084.                 return False
  1085.         return True
  1086.  
  1087.     
  1088.     def return_ok_domain(self, cookie, request):
  1089.         (req_host, erhn) = eff_request_host(request)
  1090.         domain = cookie.domain
  1091.         if cookie.version == 0 and self.strict_ns_domain & self.DomainStrictNonDomain and not (cookie.domain_specified) and domain != erhn:
  1092.             _debug('   cookie with unspecified domain does not string-compare equal to request domain')
  1093.             return False
  1094.         if cookie.version > 0 and not domain_match(erhn, domain):
  1095.             _debug('   effective request-host name %s does not domain-match RFC 2965 cookie domain %s', erhn, domain)
  1096.             return False
  1097.         if cookie.version == 0 and not ('.' + erhn).endswith(domain):
  1098.             _debug('   request-host %s does not match Netscape cookie domain %s', req_host, domain)
  1099.             return False
  1100.         return True
  1101.  
  1102.     
  1103.     def domain_return_ok(self, domain, request):
  1104.         (req_host, erhn) = eff_request_host(request)
  1105.         if not req_host.startswith('.'):
  1106.             req_host = '.' + req_host
  1107.         
  1108.         if not erhn.startswith('.'):
  1109.             erhn = '.' + erhn
  1110.         
  1111.         if not req_host.endswith(domain) or erhn.endswith(domain):
  1112.             return False
  1113.         if self.is_blocked(domain):
  1114.             _debug('   domain %s is in user block-list', domain)
  1115.             return False
  1116.         if self.is_not_allowed(domain):
  1117.             _debug('   domain %s is not in user allow-list', domain)
  1118.             return False
  1119.         return True
  1120.  
  1121.     
  1122.     def path_return_ok(self, path, request):
  1123.         _debug('- checking cookie path=%s', path)
  1124.         req_path = request_path(request)
  1125.         if not req_path.startswith(path):
  1126.             _debug('  %s does not path-match %s', req_path, path)
  1127.             return False
  1128.         return True
  1129.  
  1130.  
  1131.  
  1132. def vals_sorted_by_key(adict):
  1133.     keys = adict.keys()
  1134.     keys.sort()
  1135.     return map(adict.get, keys)
  1136.  
  1137.  
  1138. def deepvalues(mapping):
  1139.     '''Iterates over nested mapping, depth-first, in sorted order by key.'''
  1140.     values = vals_sorted_by_key(mapping)
  1141.     for obj in values:
  1142.         mapping = False
  1143.         
  1144.         try:
  1145.             obj.items
  1146.         except AttributeError:
  1147.             pass
  1148.  
  1149.         mapping = True
  1150.         for subobj in deepvalues(obj):
  1151.             yield subobj
  1152.         
  1153.         if not mapping:
  1154.             yield obj
  1155.             continue
  1156.     
  1157.  
  1158.  
  1159. class Absent:
  1160.     pass
  1161.  
  1162.  
  1163. class CookieJar:
  1164.     '''Collection of HTTP cookies.
  1165.  
  1166.     You may not need to know about this class: try
  1167.     urllib2.build_opener(HTTPCookieProcessor).open(url).
  1168.  
  1169.     '''
  1170.     non_word_re = re.compile('\\W')
  1171.     quote_re = re.compile('([\\"\\\\])')
  1172.     strict_domain_re = re.compile('\\.?[^.]*')
  1173.     domain_re = re.compile('[^.]*')
  1174.     dots_re = re.compile('^\\.+')
  1175.     magic_re = '^\\#LWP-Cookies-(\\d+\\.\\d+)'
  1176.     
  1177.     def __init__(self, policy = None):
  1178.         if policy is None:
  1179.             policy = DefaultCookiePolicy()
  1180.         
  1181.         self._policy = policy
  1182.         self._cookies_lock = _threading.RLock()
  1183.         self._cookies = { }
  1184.  
  1185.     
  1186.     def set_policy(self, policy):
  1187.         self._policy = policy
  1188.  
  1189.     
  1190.     def _cookies_for_domain(self, domain, request):
  1191.         cookies = []
  1192.         if not self._policy.domain_return_ok(domain, request):
  1193.             return []
  1194.         _debug('Checking %s for cookies to return', domain)
  1195.         cookies_by_path = self._cookies[domain]
  1196.         for path in cookies_by_path.keys():
  1197.             if not self._policy.path_return_ok(path, request):
  1198.                 continue
  1199.             
  1200.             cookies_by_name = cookies_by_path[path]
  1201.             for cookie in cookies_by_name.values():
  1202.                 if not self._policy.return_ok(cookie, request):
  1203.                     _debug('   not returning cookie')
  1204.                     continue
  1205.                 
  1206.                 _debug("   it's a match")
  1207.                 cookies.append(cookie)
  1208.             
  1209.         
  1210.         return cookies
  1211.  
  1212.     
  1213.     def _cookies_for_request(self, request):
  1214.         '''Return a list of cookies to be returned to server.'''
  1215.         cookies = []
  1216.         for domain in self._cookies.keys():
  1217.             cookies.extend(self._cookies_for_domain(domain, request))
  1218.         
  1219.         return cookies
  1220.  
  1221.     
  1222.     def _cookie_attrs(self, cookies):
  1223.         '''Return a list of cookie-attributes to be returned to server.
  1224.  
  1225.         like [\'foo="bar"; $Path="/"\', ...]
  1226.  
  1227.         The $Version attribute is also added when appropriate (currently only
  1228.         once per request).
  1229.  
  1230.         '''
  1231.         cookies.sort(key = (lambda arg: len(arg.path)), reverse = True)
  1232.         version_set = False
  1233.         attrs = []
  1234.         for cookie in cookies:
  1235.             version = cookie.version
  1236.             if not version_set:
  1237.                 version_set = True
  1238.                 if version > 0:
  1239.                     attrs.append('$Version=%s' % version)
  1240.                 
  1241.             
  1242.             if cookie.value is not None and self.non_word_re.search(cookie.value) and version > 0:
  1243.                 value = self.quote_re.sub('\\\\\\1', cookie.value)
  1244.             else:
  1245.                 value = cookie.value
  1246.             if cookie.value is None:
  1247.                 attrs.append(cookie.name)
  1248.             else:
  1249.                 attrs.append('%s=%s' % (cookie.name, value))
  1250.             if version > 0:
  1251.                 if cookie.path_specified:
  1252.                     attrs.append('$Path="%s"' % cookie.path)
  1253.                 
  1254.                 if cookie.domain.startswith('.'):
  1255.                     domain = cookie.domain
  1256.                     if not (cookie.domain_initial_dot) and domain.startswith('.'):
  1257.                         domain = domain[1:]
  1258.                     
  1259.                     attrs.append('$Domain="%s"' % domain)
  1260.                 
  1261.                 if cookie.port is not None:
  1262.                     p = '$Port'
  1263.                     if cookie.port_specified:
  1264.                         p = p + '="%s"' % cookie.port
  1265.                     
  1266.                     attrs.append(p)
  1267.                 
  1268.             cookie.port is not None
  1269.         
  1270.         return attrs
  1271.  
  1272.     
  1273.     def add_cookie_header(self, request):
  1274.         '''Add correct Cookie: header to request (urllib2.Request object).
  1275.  
  1276.         The Cookie2 header is also added unless policy.hide_cookie2 is true.
  1277.  
  1278.         '''
  1279.         _debug('add_cookie_header')
  1280.         self._cookies_lock.acquire()
  1281.         
  1282.         try:
  1283.             self._policy._now = self._now = int(time.time())
  1284.             cookies = self._cookies_for_request(request)
  1285.             attrs = self._cookie_attrs(cookies)
  1286.             if attrs:
  1287.                 if not request.has_header('Cookie'):
  1288.                     request.add_unredirected_header('Cookie', '; '.join(attrs))
  1289.                 
  1290.             
  1291.             if self._policy.rfc2965 and not (self._policy.hide_cookie2) and not request.has_header('Cookie2'):
  1292.                 for cookie in cookies:
  1293.                     if cookie.version != 1:
  1294.                         request.add_unredirected_header('Cookie2', '$Version="1"')
  1295.                         break
  1296.                         continue
  1297.                 
  1298.         finally:
  1299.             self._cookies_lock.release()
  1300.  
  1301.         self.clear_expired_cookies()
  1302.  
  1303.     
  1304.     def _normalized_cookie_tuples(self, attrs_set):
  1305.         '''Return list of tuples containing normalised cookie information.
  1306.  
  1307.         attrs_set is the list of lists of key,value pairs extracted from
  1308.         the Set-Cookie or Set-Cookie2 headers.
  1309.  
  1310.         Tuples are name, value, standard, rest, where name and value are the
  1311.         cookie name and value, standard is a dictionary containing the standard
  1312.         cookie-attributes (discard, secure, version, expires or max-age,
  1313.         domain, path and port) and rest is a dictionary containing the rest of
  1314.         the cookie-attributes.
  1315.  
  1316.         '''
  1317.         cookie_tuples = []
  1318.         boolean_attrs = ('discard', 'secure')
  1319.         value_attrs = ('version', 'expires', 'max-age', 'domain', 'path', 'port', 'comment', 'commenturl')
  1320.         for cookie_attrs in attrs_set:
  1321.             (name, value) = cookie_attrs[0]
  1322.             max_age_set = False
  1323.             bad_cookie = False
  1324.             standard = { }
  1325.             rest = { }
  1326.             for k, v in cookie_attrs[1:]:
  1327.                 lc = k.lower()
  1328.                 if lc in value_attrs or lc in boolean_attrs:
  1329.                     k = lc
  1330.                 
  1331.                 if k in boolean_attrs and v is None:
  1332.                     v = True
  1333.                 
  1334.                 if k in standard:
  1335.                     continue
  1336.                 
  1337.                 if k == 'domain':
  1338.                     if v is None:
  1339.                         _debug('   missing value for domain attribute')
  1340.                         bad_cookie = True
  1341.                         break
  1342.                     
  1343.                     v = v.lower()
  1344.                 
  1345.                 if k == 'expires':
  1346.                     if max_age_set:
  1347.                         continue
  1348.                     
  1349.                     if v is None:
  1350.                         _debug('   missing or invalid value for expires attribute: treating as session cookie')
  1351.                         continue
  1352.                     
  1353.                 
  1354.                 if k == 'max-age':
  1355.                     max_age_set = True
  1356.                     
  1357.                     try:
  1358.                         v = int(v)
  1359.                     except ValueError:
  1360.                         _debug('   missing or invalid (non-numeric) value for max-age attribute')
  1361.                         bad_cookie = True
  1362.                         break
  1363.  
  1364.                     k = 'expires'
  1365.                     v = self._now + v
  1366.                 
  1367.                 if k in value_attrs or k in boolean_attrs:
  1368.                     if v is None and k not in ('port', 'comment', 'commenturl'):
  1369.                         _debug('   missing value for %s attribute' % k)
  1370.                         bad_cookie = True
  1371.                         break
  1372.                     
  1373.                     standard[k] = v
  1374.                     continue
  1375.                 rest[k] = v
  1376.             
  1377.             if bad_cookie:
  1378.                 continue
  1379.             
  1380.             cookie_tuples.append((name, value, standard, rest))
  1381.         
  1382.         return cookie_tuples
  1383.  
  1384.     
  1385.     def _cookie_from_cookie_tuple(self, tup, request):
  1386.         (name, value, standard, rest) = tup
  1387.         domain = standard.get('domain', Absent)
  1388.         path = standard.get('path', Absent)
  1389.         port = standard.get('port', Absent)
  1390.         expires = standard.get('expires', Absent)
  1391.         version = standard.get('version', None)
  1392.         if version is not None:
  1393.             version = int(version)
  1394.         
  1395.         secure = standard.get('secure', False)
  1396.         discard = standard.get('discard', False)
  1397.         comment = standard.get('comment', None)
  1398.         comment_url = standard.get('commenturl', None)
  1399.         if path is not Absent and path != '':
  1400.             path_specified = True
  1401.             path = escape_path(path)
  1402.         else:
  1403.             path_specified = False
  1404.             path = request_path(request)
  1405.             i = path.rfind('/')
  1406.             if i != -1:
  1407.                 if version == 0:
  1408.                     path = path[:i]
  1409.                 else:
  1410.                     path = path[:i + 1]
  1411.             
  1412.             if len(path) == 0:
  1413.                 path = '/'
  1414.             
  1415.         domain_specified = domain is not Absent
  1416.         domain_initial_dot = False
  1417.         if domain_specified:
  1418.             domain_initial_dot = bool(domain.startswith('.'))
  1419.         
  1420.         if domain is Absent:
  1421.             (req_host, erhn) = eff_request_host(request)
  1422.             domain = erhn
  1423.         elif not domain.startswith('.'):
  1424.             domain = '.' + domain
  1425.         
  1426.         port_specified = False
  1427.         if port is not Absent:
  1428.             if port is None:
  1429.                 port = request_port(request)
  1430.             else:
  1431.                 port_specified = True
  1432.                 port = re.sub('\\s+', '', port)
  1433.         else:
  1434.             port = None
  1435.         if expires is Absent:
  1436.             expires = None
  1437.             discard = True
  1438.         elif expires <= self._now:
  1439.             
  1440.             try:
  1441.                 self.clear(domain, path, name)
  1442.             except KeyError:
  1443.                 pass
  1444.  
  1445.             _debug("Expiring cookie, domain='%s', path='%s', name='%s'", domain, path, name)
  1446.             return None
  1447.         return Cookie(version, name, value, port, port_specified, domain, domain_specified, domain_initial_dot, path, path_specified, secure, expires, discard, comment, comment_url, rest)
  1448.  
  1449.     
  1450.     def _cookies_from_attrs_set(self, attrs_set, request):
  1451.         cookie_tuples = self._normalized_cookie_tuples(attrs_set)
  1452.         cookies = []
  1453.         for tup in cookie_tuples:
  1454.             cookie = self._cookie_from_cookie_tuple(tup, request)
  1455.             if cookie:
  1456.                 cookies.append(cookie)
  1457.                 continue
  1458.         
  1459.         return cookies
  1460.  
  1461.     
  1462.     def _process_rfc2109_cookies(self, cookies):
  1463.         rfc2109_as_ns = getattr(self._policy, 'rfc2109_as_netscape', None)
  1464.         if rfc2109_as_ns is None:
  1465.             rfc2109_as_ns = not (self._policy.rfc2965)
  1466.         
  1467.         for cookie in cookies:
  1468.             if cookie.version == 1:
  1469.                 cookie.rfc2109 = True
  1470.                 if rfc2109_as_ns:
  1471.                     cookie.version = 0
  1472.                 
  1473.             rfc2109_as_ns
  1474.         
  1475.  
  1476.     
  1477.     def make_cookies(self, response, request):
  1478.         '''Return sequence of Cookie objects extracted from response object.'''
  1479.         headers = response.info()
  1480.         rfc2965_hdrs = headers.getheaders('Set-Cookie2')
  1481.         ns_hdrs = headers.getheaders('Set-Cookie')
  1482.         rfc2965 = self._policy.rfc2965
  1483.         netscape = self._policy.netscape
  1484.         if not not rfc2965_hdrs or not ns_hdrs:
  1485.             if not not ns_hdrs or not rfc2965:
  1486.                 if (not rfc2965_hdrs or not netscape or not netscape) and not rfc2965:
  1487.                     return []
  1488.                 
  1489.                 try:
  1490.                     cookies = self._cookies_from_attrs_set(split_header_words(rfc2965_hdrs), request)
  1491.                 except Exception:
  1492.                     not rfc2965
  1493.                     not rfc2965
  1494.                     _warn_unhandled_exception()
  1495.                     cookies = []
  1496.                 except:
  1497.                     not rfc2965
  1498.  
  1499.                 if ns_hdrs and netscape:
  1500.                     
  1501.                     try:
  1502.                         ns_cookies = self._cookies_from_attrs_set(parse_ns_headers(ns_hdrs), request)
  1503.                     except Exception:
  1504.                         not rfc2965
  1505.                         not rfc2965
  1506.                         _warn_unhandled_exception()
  1507.                         ns_cookies = []
  1508.                     except:
  1509.                         not rfc2965
  1510.  
  1511.                     self._process_rfc2109_cookies(ns_cookies)
  1512.                     if rfc2965:
  1513.                         lookup = { }
  1514.                         for cookie in cookies:
  1515.                             lookup[(cookie.domain, cookie.path, cookie.name)] = None
  1516.                         
  1517.                         
  1518.                         def no_matching_rfc2965(ns_cookie, lookup = lookup):
  1519.                             key = (ns_cookie.domain, ns_cookie.path, ns_cookie.name)
  1520.                             return key not in lookup
  1521.  
  1522.                         ns_cookies = filter(no_matching_rfc2965, ns_cookies)
  1523.                     
  1524.                     if ns_cookies:
  1525.                         cookies.extend(ns_cookies)
  1526.                     
  1527.                 
  1528.         return cookies
  1529.  
  1530.     
  1531.     def set_cookie_if_ok(self, cookie, request):
  1532.         """Set a cookie if policy says it's OK to do so."""
  1533.         self._cookies_lock.acquire()
  1534.         
  1535.         try:
  1536.             self._policy._now = self._now = int(time.time())
  1537.             if self._policy.set_ok(cookie, request):
  1538.                 self.set_cookie(cookie)
  1539.         finally:
  1540.             self._cookies_lock.release()
  1541.  
  1542.  
  1543.     
  1544.     def set_cookie(self, cookie):
  1545.         '''Set a cookie, without checking whether or not it should be set.'''
  1546.         c = self._cookies
  1547.         self._cookies_lock.acquire()
  1548.         
  1549.         try:
  1550.             if cookie.domain not in c:
  1551.                 c[cookie.domain] = { }
  1552.             
  1553.             c2 = c[cookie.domain]
  1554.             if cookie.path not in c2:
  1555.                 c2[cookie.path] = { }
  1556.             
  1557.             c3 = c2[cookie.path]
  1558.             c3[cookie.name] = cookie
  1559.         finally:
  1560.             self._cookies_lock.release()
  1561.  
  1562.  
  1563.     
  1564.     def extract_cookies(self, response, request):
  1565.         '''Extract cookies from response, where allowable given the request.'''
  1566.         _debug('extract_cookies: %s', response.info())
  1567.         self._cookies_lock.acquire()
  1568.         
  1569.         try:
  1570.             self._policy._now = self._now = int(time.time())
  1571.             for cookie in self.make_cookies(response, request):
  1572.                 if self._policy.set_ok(cookie, request):
  1573.                     _debug(' setting cookie: %s', cookie)
  1574.                     self.set_cookie(cookie)
  1575.                     continue
  1576.         finally:
  1577.             self._cookies_lock.release()
  1578.  
  1579.  
  1580.     
  1581.     def clear(self, domain = None, path = None, name = None):
  1582.         '''Clear some cookies.
  1583.  
  1584.         Invoking this method without arguments will clear all cookies.  If
  1585.         given a single argument, only cookies belonging to that domain will be
  1586.         removed.  If given two arguments, cookies belonging to the specified
  1587.         path within that domain are removed.  If given three arguments, then
  1588.         the cookie with the specified name, path and domain is removed.
  1589.  
  1590.         Raises KeyError if no matching cookie exists.
  1591.  
  1592.         '''
  1593.         if name is not None:
  1594.             if domain is None or path is None:
  1595.                 raise ValueError('domain and path must be given to remove a cookie by name')
  1596.             path is None
  1597.             del self._cookies[domain][path][name]
  1598.         elif path is not None:
  1599.             if domain is None:
  1600.                 raise ValueError('domain must be given to remove cookies by path')
  1601.             domain is None
  1602.             del self._cookies[domain][path]
  1603.         elif domain is not None:
  1604.             del self._cookies[domain]
  1605.         else:
  1606.             self._cookies = { }
  1607.  
  1608.     
  1609.     def clear_session_cookies(self):
  1610.         """Discard all session cookies.
  1611.  
  1612.         Note that the .save() method won't save session cookies anyway, unless
  1613.         you ask otherwise by passing a true ignore_discard argument.
  1614.  
  1615.         """
  1616.         self._cookies_lock.acquire()
  1617.         
  1618.         try:
  1619.             for cookie in self:
  1620.                 if cookie.discard:
  1621.                     self.clear(cookie.domain, cookie.path, cookie.name)
  1622.                     continue
  1623.         finally:
  1624.             self._cookies_lock.release()
  1625.  
  1626.  
  1627.     
  1628.     def clear_expired_cookies(self):
  1629.         """Discard all expired cookies.
  1630.  
  1631.         You probably don't need to call this method: expired cookies are never
  1632.         sent back to the server (provided you're using DefaultCookiePolicy),
  1633.         this method is called by CookieJar itself every so often, and the
  1634.         .save() method won't save expired cookies anyway (unless you ask
  1635.         otherwise by passing a true ignore_expires argument).
  1636.  
  1637.         """
  1638.         self._cookies_lock.acquire()
  1639.         
  1640.         try:
  1641.             now = time.time()
  1642.             for cookie in self:
  1643.                 if cookie.is_expired(now):
  1644.                     self.clear(cookie.domain, cookie.path, cookie.name)
  1645.                     continue
  1646.         finally:
  1647.             self._cookies_lock.release()
  1648.  
  1649.  
  1650.     
  1651.     def __iter__(self):
  1652.         return deepvalues(self._cookies)
  1653.  
  1654.     
  1655.     def __len__(self):
  1656.         '''Return number of contained cookies.'''
  1657.         i = 0
  1658.         for cookie in self:
  1659.             i = i + 1
  1660.         
  1661.         return i
  1662.  
  1663.     
  1664.     def __repr__(self):
  1665.         r = []
  1666.         for cookie in self:
  1667.             r.append(repr(cookie))
  1668.         
  1669.         return '<%s[%s]>' % (self.__class__, ', '.join(r))
  1670.  
  1671.     
  1672.     def __str__(self):
  1673.         r = []
  1674.         for cookie in self:
  1675.             r.append(str(cookie))
  1676.         
  1677.         return '<%s[%s]>' % (self.__class__, ', '.join(r))
  1678.  
  1679.  
  1680.  
  1681. class LoadError(IOError):
  1682.     pass
  1683.  
  1684.  
  1685. class FileCookieJar(CookieJar):
  1686.     '''CookieJar that can be loaded from and saved to a file.'''
  1687.     
  1688.     def __init__(self, filename = None, delayload = False, policy = None):
  1689.         '''
  1690.         Cookies are NOT loaded from the named file until either the .load() or
  1691.         .revert() method is called.
  1692.  
  1693.         '''
  1694.         CookieJar.__init__(self, policy)
  1695.         if filename is not None:
  1696.             
  1697.             try:
  1698.                 filename + ''
  1699.             raise ValueError('filename must be string-like')
  1700.  
  1701.         
  1702.         self.filename = filename
  1703.         self.delayload = bool(delayload)
  1704.  
  1705.     
  1706.     def save(self, filename = None, ignore_discard = False, ignore_expires = False):
  1707.         '''Save cookies to a file.'''
  1708.         raise NotImplementedError()
  1709.  
  1710.     
  1711.     def load(self, filename = None, ignore_discard = False, ignore_expires = False):
  1712.         '''Load cookies from a file.'''
  1713.         if filename is None:
  1714.             if self.filename is not None:
  1715.                 filename = self.filename
  1716.             else:
  1717.                 raise ValueError(MISSING_FILENAME_TEXT)
  1718.         self.filename is not None
  1719.         f = open(filename)
  1720.         
  1721.         try:
  1722.             self._really_load(f, filename, ignore_discard, ignore_expires)
  1723.         finally:
  1724.             f.close()
  1725.  
  1726.  
  1727.     
  1728.     def revert(self, filename = None, ignore_discard = False, ignore_expires = False):
  1729.         """Clear all cookies and reload cookies from a saved file.
  1730.  
  1731.         Raises LoadError (or IOError) if reversion is not successful; the
  1732.         object's state will not be altered if this happens.
  1733.  
  1734.         """
  1735.         if filename is None:
  1736.             if self.filename is not None:
  1737.                 filename = self.filename
  1738.             else:
  1739.                 raise ValueError(MISSING_FILENAME_TEXT)
  1740.         self.filename is not None
  1741.         self._cookies_lock.acquire()
  1742.         
  1743.         try:
  1744.             old_state = copy.deepcopy(self._cookies)
  1745.             self._cookies = { }
  1746.             
  1747.             try:
  1748.                 self.load(filename, ignore_discard, ignore_expires)
  1749.             except (LoadError, IOError):
  1750.                 self._cookies = old_state
  1751.                 raise 
  1752.  
  1753.         finally:
  1754.             self._cookies_lock.release()
  1755.  
  1756.  
  1757.  
  1758. from _LWPCookieJar import LWPCookieJar, lwp_cookie_str
  1759. from _MozillaCookieJar import MozillaCookieJar
  1760.